<template>
  <div class="bg-white m-4 mr-0 overflow-hidden zcate">

    <div class="flex px-2 py-1.5 items-center basic-tree-header">
      <div class="flex flex-1 justify-self-stretch items-center cursor-pointer">
        <!--        <vxe-select v-model="demo1.value10" placeholder="默认尺寸">-->
        <!--          <vxe-option v-for="num in 15" :key="num" :value="num" :label="`选项${num}`"></vxe-option>-->
        <!--        </vxe-select>-->
        <div>
          项目：
          <vxe-select v-model="taskTree.projid" style="width: 182px" :options="taskTree.projs" size="medium" @change="projChange"></vxe-select>
          <vxe-button icon="vxe-icon--plus" title="新增阶段" circle @click="insertEvent(-1)" style="margin-left: 6px;margin-right: 0"></vxe-button>
        </div>
        <!--        <vxe-input v-model="taskTree.projname" suffix-icon="vxe-icon&#45;&#45;search" readonly style="width: 100%;cursor: pointer" @click="selectProj"></vxe-input>-->
        <!--        <vxe-button icon="vxe-icon&#45;&#45;refresh" title="刷新" circle @click="refreshClick" style="margin-left: 4px;margin-right: 2px"></vxe-button>-->
        <!--        <vxe-button icon="vxe-icon&#45;&#45;dot" title="根目录" circle @click="rootClick" style="margin-left: 2px;margin-right: 2px"></vxe-button>-->
        <!--        <vxe-button icon="vxe-icon&#45;&#45;caret-bottom" title="展开" circle @click="$refs.xCate.setAllTreeExpand(true)" style="margin-left: 2px;margin-right: 2px"></vxe-button>-->
        <!--        <vxe-button icon="vxe-icon&#45;&#45;caret-top" title="折叠" circle @click="$refs.xCate.clearTreeExpand()" style="margin-left: 2px;margin-right: 2px"></vxe-button>-->
      </div>
    </div>

    <hr/>
    <!--    :edit-config="{trigger: 'dblclick', mode: 'cell'}"-->
    <div style="margin: 4px" class="proj-tree">
      <vxe-table
          border="none"
          size="mini"
          :show-header="false"
          highlight-current-row
          highlight-hover-row
          row-key
          keep-source
          ref="xTable"
          class="sortable-row-demo"
          @cell-click="cellClickEvent"
          :edit-config="{trigger: 'manual', mode: 'row'}"
          :scroll-y="{enabled: false}"
          @edit-closed="editClosedEvent"
          :data="taskTree.stages">
        <vxe-column width="20">
          <template #default>
                    <span class="drag-btn" style="text-align: center">
                      <i class="vxe-icon--menu"></i>
                    </span>
          </template>
          <template #header>
            <vxe-tooltip v-model="taskTree.showHelpTip" content="按住后可以上下拖动排序！" enterable>
              <i class="vxe-icon--question" @click="taskTree.showHelpTip = !taskTree.showHelpTip"></i>
            </vxe-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="name" title="name" :edit-render="{}" width="192">
          <template #edit="{ row }">
            <vxe-input v-model="row.name" type="text" placeholder="请输入名称" size="mini"></vxe-input>
          </template>
        </vxe-column>
        <!--        <vxe-column :edit-render="{}" field="sex" title="Sex"></vxe-column>-->
        <vxe-column title="操作" width="60">
          <template #default="{ row }">
            <FormOutlined @click="editRowEvent(row)" style="font-size: 15px;margin-left: 11px;color: #2874C5"/>
            <DeleteOutlined @click="removeEvent(row)" style="font-size: 15px;margin-left: 10px;color: #ED6F6F"/>
            <!--            <template v-if="$refs.xTable.isActiveByRow(row)" style="color:red ">-->
            <!--              <i class="vxe-icon&#45;&#45;edit-outline"></i>-->
            <!--              &lt;!&ndash;              <vxe-button @click="saveRowEvent(row)">保存</vxe-button>&ndash;&gt;-->
            <!--              &lt;!&ndash;              <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>&ndash;&gt;-->
            <!--            </template>-->
            <!--            <template v-else style="color:red ">-->
            <!--&lt;!&ndash;              <i class="vxe-icon&#45;&#45;edit-outline" @click="editRowEvent(row)"></i>&ndash;&gt;-->
            <!--              &lt;!&ndash;              <vxe-button @click="editRowEvent(row)">编辑</vxe-button>&ndash;&gt;-->
            <!--            -->
            <!--            </template>-->
          </template>
        </vxe-column>
      </vxe-table>


      <!--      <vxe-table-->
      <!--          border-->
      <!--          resizable-->
      <!--          show-overflow-->
      <!--          ref="xTable"-->
      <!--          :loading="taskTree.loading"-->
      <!--          :data="taskTree.tableData"-->
      <!--          :edit-config="{trigger: 'manual', mode: 'row'}">-->
      <!--        <vxe-column type="seq" width="60"></vxe-column>-->
      <!--        <vxe-column field="role" title="Role" :edit-render="{}">-->
      <!--          <template #edit="{ row }">-->
      <!--            <vxe-input v-model="row.role" type="text" placeholder="请输入昵称"></vxe-input>-->
      <!--          </template>-->
      <!--        </vxe-column>-->
      <!--        <vxe-column width="35">-->
      <!--          <template #default>-->
      <!--                      <span class="drag-btn" style="text-align: center">-->
      <!--                        <i class="vxe-icon&#45;&#45;menu"></i>-->
      <!--                      </span>-->
      <!--          </template>-->
      <!--          <template #header>-->
      <!--            <vxe-tooltip v-model="taskTree.showHelpTip" content="按住后可以上下拖动排序！" enterable>-->
      <!--              <i class="vxe-icon&#45;&#45;question" @click="taskTree.showHelpTip = !taskTree.showHelpTip"></i>-->
      <!--            </vxe-tooltip>-->
      <!--          </template>-->
      <!--        </vxe-column>-->

      <!--        <vxe-column title="操作" width="160">-->
      <!--          <template #default="{ row }">-->
      <!--            <template v-if="$refs.xTable.isActiveByRow(row)">-->
      <!--              <vxe-button @click="saveRowEvent(row)">保存</vxe-button>-->
      <!--              <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>-->
      <!--            </template>-->
      <!--            <template v-else>-->
      <!--              <vxe-button @click="editRowEvent(row)">编辑</vxe-button>-->
      <!--            </template>-->
      <!--          </template>-->
      <!--        </vxe-column>-->
      <!--      </vxe-table>-->

    </div>
    <!--    <TreeModal ref="xTree" @select="projSelect"/>-->
  </div>
</template>
<script lang="ts" setup>
import {onMounted, onUnmounted, reactive, ref, nextTick} from 'vue'
import XEUtils from 'xe-utils'
import {VXETable, VxeGridInstance, VxeGridProps, VxeTableEvents, VxeTableInstance} from 'vxe-table'
import Sortable from 'sortablejs'
import {defHttp} from "/@/utils/http/axios";
import TreeModal from '/@/comps/org/TreeModal.vue';
import {DeleteOutlined, FormOutlined} from '@ant-design/icons-vue';

const emit = defineEmits(['select']);

const xTable = ref({} as VxeTableInstance)

const taskTree = reactive({
  showHelpTip: false,
  projid: '' as any,
  loading: false,
  projname: '' as any,
  projs: [],
  stages: []
})

let sortable1: any


const rowDrop = () => {
  const $table = xTable.value
  sortable1 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
    handle: '.drag-btn',
    onEnd: (sortableEvent) => {
      const newIndex = sortableEvent.newIndex as number
      const oldIndex = sortableEvent.oldIndex as number
      const currRow = taskTree.tableData.splice(oldIndex, 1)[0]
      taskTree.tableData.splice(newIndex, 0, currRow)
    }
  })
}

let initTime: any
nextTick(() => {
  // 加载完成之后在绑定拖动事件
  initTime = setTimeout(() => {
    rowDrop()
  }, 500)
})

onUnmounted(() => {
  clearTimeout(initTime)
  if (sortable1) {
    sortable1.destroy()
  }
})

// const xTree = ref({} as any)
//
// function selectProj() {
//   xTree.value.open({url:"/pm/proj/main/tree"});
// }
//
// function projSelect(data) {
//   console.log(data);
//   if (data != null) {
//     if(data.type&&data.type=="cate"){
//       alert("请选择项目");
//     }else{
//       taskTree.projname = data.name;
//       taskTree.projid = data.id;
//     }
//   } else {
//     taskTree.projname = null;
//     taskTree.projid = null;
//   }
// }

async function fetch() {
  taskTree.projs = await defHttp.get({url: "/pm/proj/main/list"});
}

onMounted(() => {
  fetch();
})

let projid = '';

async function projChange(item) {
  console.log(item.value);
  projid = item.value;
  taskTree.stages = await defHttp.get({url: "/pm/proj/stage/list?projid=" + projid});
}

const insertEvent = async (row: any) => {
  if (projid == '') {
    await VXETable.modal.message({content: '请先选择项目', status: 'warning'});
    return;
  }
  const $table = xTable.value;
  const record = {
    id: guid().replaceAll("-", ""),
    name: '',
    type: 'new',
    projid: projid,
  }
  const {row: newRow} = await $table.insertAt(record, row)
  await $table.setActiveCell(newRow, 'name')
}


const editRowEvent = (row) => {
  const $table = xTable.value
  $table.setActiveRow(row);
}

const editClosedEvent: VxeTableEvents.EditClosed = async ({row, column}) => {
  const $table = xTable.value
  const field = column.property
  const cellValue = row[field];
  if (row.type == 'new') {
    console.log("新增的每次都去更新")
    await defHttp.post({url: "/pm/proj/stage", data: row});
    // row.type='old';
  }
  // 判断单元格值是否被修改
  else if ($table.isUpdateByRow(row, field)) {
    console.log("修改");
    await defHttp.put({url: "/pm/proj/stage", data: row});
    // setTimeout(() => {
    //   VXETable.modal.message({
    //     content: `局部保存成功！ ${field}=${cellValue}`,
    //     status: 'success'
    //   })
    //   // 局部更新单元格为已保存状态
    //   $table.reloadRow(row, null, field)
    // }, 300)
  }
}

function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

const cellClickEvent: VxeTableEvents.CellClick = ({column, row, triggerTreeNode}) => {
  emit('select', {id: row.id, name: row.name});
  // if (!triggerTreeNode) {
  //   xTree.value.toggleTreeExpand(row);
  // }
}

const removeEvent = async (row: any) => {
  const type = await VXETable.modal.confirm('您确定要删除该数据?')
  if (type === 'confirm') {
    const $table = xTable.value
    await $table.remove(row)
  }
}

</script>
<style >
.zcate .vxe-body--row {
  cursor: pointer;
}

.zcate ::-webkit-scrollbar-track {
  background-color: #FFFFFF !important;
}

.zcate .vxe-table--render-default.size--mini .vxe-body--column.col--ellipsis {
  height: 28px;
}

.proj-tree .vxe-table--render-default .vxe-cell{
  padding-left: 2px ;
  padding-right: 2px ;
}
</style>
